package avicit.bdp.dgs.common.controller;

import avicit.bdp.common.service.dto.DataSourceDTO;
import avicit.bdp.common.service.service.DataSourceService;
import avicit.bdp.common.vo.CommonResVo;
import avicit.bdp.core.constant.Constants;
import avicit.bdp.core.datasource.enums.DataSourceType;
import avicit.bdp.dgs.metadata.service.MetadataModelService;
import avicit.bdp.dgs.metadata.service.MetadataTableService;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import com.github.pagehelper.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = "数据源查询接口")
@RequestMapping("/api/bdp/dgs/common/datasource")
public class DgsDataSourceController {

  @Resource private DataSourceService dataSourceService;
  @Resource private MetadataModelService metadataModelService;
  @Resource private MetadataTableService metadataTableService;

  @ApiOperation(value = "获取所有数据源类型")
  @GetMapping("getAllDataSourceTypeList")
  public ResponseMsg<List<String>> getAllDataSourceTypeList() {
    ResponseMsg<List<String>> responseMsg = new ResponseMsg<>();
    List<String> list =
        Arrays.stream(DataSourceType.values())
            .sorted(Comparator.comparingInt(DataSourceType::getVal))
            .map(item -> item.name().toLowerCase())
            .collect(Collectors.toList());
    responseMsg.setResponseBody(list);
    return responseMsg;
  }

  @ApiOperation(value = "获取数据源类型")
  @GetMapping("getDataSourceTypeList")
  public ResponseMsg<List<String>> getDataSourceTypeList() {
    ResponseMsg<List<String>> responseMsg = new ResponseMsg<>();
    List<String> list = metadataModelService.getDataSourceTypeList(Constants.STATUS_ONE);
    responseMsg.setResponseBody(list);
    return responseMsg;
  }

  /**
   * 查询元数据采集数据源列表
   *
   * @param keyWords key word
   */
  @ApiOperation(value = "查询元数据数据源列表")
  @ApiImplicitParam(name = "keyWords", value = "关键字", dataType = "String")
  @GetMapping(value = "/list")
  public ResponseMsg<List<CommonResVo>> queryMetadataDataSourceList(
      @RequestParam(value = "keyWords", required = false) String keyWords) {

    ResponseMsg<List<CommonResVo>> responseMsg = new ResponseMsg<>();
    List<DataSourceDTO> dataSourceList = dataSourceService.queryMetadataDataSourceList(keyWords);
    List<CommonResVo> resultList = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(dataSourceList)) {
      for(DataSourceDTO item : dataSourceList){
        CommonResVo commonResVo = new CommonResVo();
        commonResVo.setId(item.getId());
        commonResVo.setName(item.getDatasourceName());
        commonResVo.setSecretLevel(item.getSecretLevel());
        resultList.add(commonResVo);
      }
    }
    responseMsg.setResponseBody(resultList);
    return responseMsg;
  }

  /**
   * 查询数据源列表
   *
   * @param type data source typ
   * @param structure 结构：0-结构化 1-非结构化 2-半结构化
   * @param keyWords key word
   */
  @ApiOperation(value = "查询数据源列表")
  @ApiImplicitParams({
    @ApiImplicitParam(name = "type", value = "数据源类型", dataType = "String"),
    @ApiImplicitParam(name = "structure", value = "数据源结构", dataType = "Int"),
    @ApiImplicitParam(name = "keyWords", value = "关键字", dataType = "String")
  })
  @GetMapping(value = "/queryDataSourceList")
  public ResponseMsg<List<CommonResVo>> queryDataSourceList(
      @RequestParam(value = "type", required = false) String type,
      @RequestParam(value = "structure", required = false) Integer structure,
      @RequestParam(value = "keyWords", required = false) String keyWords) {

    if (StringUtils.isNotBlank(type)) {
      type = type.toLowerCase();
    }
    ResponseMsg<List<CommonResVo>> responseMsg = new ResponseMsg<>();
    List<DataSourceDTO> dataSourceList;
    // 文档密级
    List<String> wordSecretList = ThreadContextHelper.getWordSecretList();
    if ("rdbms".equalsIgnoreCase(type)) {
      List<String> rdbmsNameList = DataSourceType.getRDBMSNameList();
      dataSourceList = dataSourceService.getDsListByTypeListWithPerm(rdbmsNameList, structure, keyWords, wordSecretList);
    } else {
      dataSourceList = dataSourceService.queryDataSourceList(type, structure, keyWords, wordSecretList);
    }

    List<CommonResVo> resultList = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(dataSourceList)) {
      for(DataSourceDTO item : dataSourceList){
        CommonResVo commonResVo = new CommonResVo();
        commonResVo.setId(item.getId());
        commonResVo.setName(item.getDatasourceName());
        commonResVo.setSecretLevel(item.getSecretLevel());
        resultList.add(commonResVo);
      }
    }
    responseMsg.setResponseBody(resultList);
    return responseMsg;
  }

  @ApiOperation(value = "分页查询表数据")
  @ApiImplicitParams({
    @ApiImplicitParam(
        value = "数据源类型",
        name = "datasourceType",
        dataType = "String",
        paramType = "query"),
    @ApiImplicitParam(
        value = "数据源",
        name = "dataSourceId",
        dataType = "String",
        paramType = "query"),
    @ApiImplicitParam(value = "空间ID", name = "projectId", dataType = "String", paramType = "query"),
    @ApiImplicitParam(
        value = "数据目录ID",
        name = "catalogId",
        dataType = "String",
        paramType = "query"),
    @ApiImplicitParam(value = "查询关键词", name = "keyWords", dataType = "String", paramType = "query"),
    @ApiImplicitParam(value = "状态", name = "status", dataType = "Int", paramType = "query"),
    @ApiImplicitParam(value = "类型", name = "type", dataType = "Int", paramType = "query"),
    @ApiImplicitParam(value = "当前页", name = "pageNo", dataType = "Int", paramType = "query"),
    @ApiImplicitParam(value = "每页大小", name = "pageSize", dataType = "Int", paramType = "query")
  })
  @GetMapping(value = "/table/page")
  public ResponseMsg<QueryRespBean<CommonResVo>> getTablePageList(
      @RequestParam(required = false) String datasourceType,
      @RequestParam(required = false) String dataSourceId,
      @RequestParam(required = false) String projectId,
      @RequestParam(required = false) String catalogId,
      @RequestParam(required = false) String keyWords,
      @RequestParam(required = false) Integer status,
      @RequestParam(required = false) Integer type,
      @RequestParam(defaultValue = "1") Integer pageNo,
      @RequestParam(defaultValue = "10") Integer pageSize)
      throws Exception {

    ResponseMsg<QueryRespBean<CommonResVo>> responseMsg = new ResponseMsg<>();
    Page<CommonResVo> pageList =
        metadataTableService.getPageList2(
            datasourceType,
            dataSourceId,
            projectId,
            catalogId,
            keyWords,
            status,
            type,
            pageNo,
            pageSize);

    QueryRespBean<CommonResVo> queryRespBean = new QueryRespBean<>();
    queryRespBean.setResult(pageList);
    responseMsg.setResponseBody(queryRespBean);

    return responseMsg;
  }

  @ApiOperation(value = "分页查询列数据")
  @ApiImplicitParams({
    @ApiImplicitParam(
        value = "表ID",
        name = "tableId",
        dataType = "String",
        paramType = "query",
        required = true),
    @ApiImplicitParam(value = "查询关键词", name = "keyWords", dataType = "String", paramType = "query"),
    @ApiImplicitParam(value = "当前页", name = "pageNo", dataType = "Int", paramType = "query"),
    @ApiImplicitParam(value = "每页大小", name = "pageSize", dataType = "Int", paramType = "query")
  })
  @GetMapping(value = "/table/column/page")
  public ResponseMsg<QueryRespBean<CommonResVo>> getColumnPageList(
      @RequestParam String tableId,
      @RequestParam(required = false) String keyWords,
      @RequestParam(defaultValue = "1") Integer pageNo,
      @RequestParam(defaultValue = "10") Integer pageSize)
      throws Exception {

    ResponseMsg<QueryRespBean<CommonResVo>> responseMsg = new ResponseMsg<>();
    Page<CommonResVo> pageList =
        metadataTableService.getColumnPageList(tableId, keyWords, pageNo, pageSize);
    QueryRespBean<CommonResVo> queryRespBean = new QueryRespBean<>();
    queryRespBean.setResult(pageList);
    responseMsg.setResponseBody(queryRespBean);

    return responseMsg;
  }
}
